<template>
  <view class="qr-modal" v-if="visible" @click="handleClose">
    <view class="modal-content" @click.stop>
      <view class="modal-header">
        <text class="modal-title">{{ title }}</text>
        <text class="modal-close" @click="handleClose">×</text>
      </view>
      
      <view class="qr-content">
        <!-- 二维码区域 -->
        <view class="qr-code-section">
          <!-- 使用图片显示二维码，而不是canvas -->
          <view class="qr-image-container" v-if="qrImageUrl">
            <image 
              :src="qrImageUrl" 
              class="qr-image"
              mode="aspectFit"
              @error="handleImageError"
            ></image>
          </view>
          
          <!-- 二维码占位图 -->
          <view class="qr-placeholder" v-else>
            <view class="placeholder-content">
              <text class="placeholder-icon">📱</text>
              <text class="placeholder-text">{{ qrLoading ? '生成中...' : '二维码加载失败' }}</text>
            </view>
          </view>
        </view>
        
        <!-- 描述信息 -->
        <view class="qr-desc" v-if="description">
          <text class="desc-text">{{ description }}</text>
        </view>
        
        <!-- 额外信息 -->
        <view class="qr-info" v-if="extraInfo">
          <text class="info-label">{{ extraInfo.label }}：</text>
          <text class="info-value">{{ extraInfo.value }}</text>
          <text class="info-copy" @click="copyInfo" v-if="extraInfo.copyable">复制</text>
        </view>
        
        <!-- 操作按钮 -->
        <view class="qr-actions" v-if="actions && actions.length">
          <button 
            v-for="(action, index) in actions" 
            :key="index"
            class="action-btn"
            :class="action.type || 'default'"
            @click="handleAction(action)"
          >
            {{ action.text }}
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
/**
 * 二维码弹窗组件
 * @author 王勇程 <laughskydragon@qq.com>
 */
import { copyToClipboard } from '@/utils/common'

export default {
  name: 'QrModal',
  
  props: {
    // 是否显示
    visible: {
      type: Boolean,
      default: false
    },
    
    // 标题
    title: {
      type: String,
      default: '二维码'
    },
    
    // 二维码内容
    content: {
      type: String,
      default: ''
    },
    
    // 二维码图片URL（优先使用）
    qrImageUrl: {
      type: String,
      default: ''
    },
    
    // 描述信息
    description: {
      type: String,
      default: ''
    },
    
    // 额外信息
    extraInfo: {
      type: Object,
      default: null
      // { label: '邀请码', value: 'ABC123', copyable: true }
    },
    
    // 操作按钮
    actions: {
      type: Array,
      default: () => []
      // [{ text: '分享给好友', type: 'primary', action: 'share' }]
    },
    
    // 二维码大小
    qrSize: {
      type: Number,
      default: 400
    }
  },
  
  data() {
    return {
      qrLoading: false,
      imageError: false
    }
  },
  
  watch: {
    visible(newVal) {
      if (newVal) {
        this.imageError = false
        if (!this.qrImageUrl && this.content) {
          this.generateQRCodeUrl()
        }
      }
    },
    
    content(newVal) {
      if (this.visible && newVal && !this.qrImageUrl) {
        this.generateQRCodeUrl()
      }
    }
  },
  
  methods: {
    // 关闭弹窗
    handleClose() {
      this.$emit('close')
    },
    
    // 生成二维码URL（使用在线服务）
    generateQRCodeUrl() {
      if (!this.content) return
      
      this.qrLoading = true
      
      try {
        // 使用在线二维码生成服务
        const encodedContent = encodeURIComponent(this.content)
        const qrUrl = `https://api.qrserver.com/v1/create-qr-code/?size=${this.qrSize}x${this.qrSize}&data=${encodedContent}`
        
        // 触发父组件更新二维码URL
        this.$emit('qr-generated', qrUrl)
        
        this.qrLoading = false
      } catch (error) {
        console.error('生成二维码失败:', error)
        this.qrLoading = false
        this.imageError = true
      }
    },
    
    // 处理图片加载错误
    handleImageError() {
      this.imageError = true
      this.qrLoading = false
    },
    
    // 复制额外信息
    async copyInfo() {
      if (this.extraInfo && this.extraInfo.value) {
        try {
          await copyToClipboard(this.extraInfo.value)
        } catch (error) {
          console.error('复制失败:', error)
          uni.showToast({
            title: '复制失败',
            icon: 'none'
          })
        }
      }
    },
    
    // 处理操作按钮点击
    handleAction(action) {
      this.$emit('action', action)
    }
  }
}
</script>

<style scoped>
.qr-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background-color: #FFF;
  border-radius: 20rpx;
  padding: 40rpx;
  margin: 0 60rpx;
  max-width: 600rpx;
  width: 100%;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.modal-close {
  font-size: 48rpx;
  color: #999;
  line-height: 1;
  cursor: pointer;
}

.qr-content {
  text-align: center;
}

.qr-code-section {
  position: relative;
  display: inline-block;
  margin-bottom: 30rpx;
}

.qr-image-container {
  border: 1rpx solid #E5E5E5;
  border-radius: 12rpx;
  padding: 20rpx;
  background-color: #FFF;
}

.qr-image {
  width: 400rpx;
  height: 400rpx;
  display: block;
}

.qr-placeholder {
  width: 400rpx;
  height: 400rpx;
  border: 1rpx solid #E5E5E5;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #F8F8F8;
}

.placeholder-content {
  text-align: center;
}

.placeholder-icon {
  font-size: 80rpx;
  display: block;
  margin-bottom: 20rpx;
}

.placeholder-text {
  font-size: 24rpx;
  color: #999;
}

.qr-desc {
  margin-bottom: 30rpx;
}

.desc-text {
  font-size: 24rpx;
  color: #666;
  line-height: 1.5;
}

.qr-info {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 40rpx;
  padding: 20rpx;
  background-color: #F5F5F5;
  border-radius: 12rpx;
}

.info-label {
  font-size: 28rpx;
  color: #333;
}

.info-value {
  font-size: 28rpx;
  font-weight: bold;
  color: #FF4444;
  margin: 0 20rpx;
}

.info-copy {
  font-size: 24rpx;
  color: #FF4444;
  padding: 8rpx 16rpx;
  border: 1rpx solid #FF4444;
  border-radius: 8rpx;
  cursor: pointer;
}

.qr-actions {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.action-btn {
  width: 100%;
  padding: 24rpx;
  border-radius: 12rpx;
  font-size: 28rpx;
  border: none;
  cursor: pointer;
}

.action-btn.default {
  background-color: #F5F5F5;
  color: #333;
}

.action-btn.primary {
  background: linear-gradient(135deg, #FF4444 0%, #FF6666 100%);
  color: #FFF;
}

.action-btn.success {
  background-color: #07C160;
  color: #FFF;
}

.action-btn.warning {
  background-color: #FF9500;
  color: #FFF;
}
</style>